//
//  LPStarRateView.swift
//  StarEvaluation
//
//  Created by zwb on 2016/12/9.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit

// 整个✨， 半个✨， 不完整✨
enum RateStyle {
    case wholeStar, halfStar, incompleteStar
}

class LPStarRateView: UIView {

    var isAnimation = false
    var rateStyle: RateStyle = .wholeStar
    fileprivate var foregroundStarView: UIView!
    fileprivate var backgroundStarView: UIView!
    fileprivate var numberOfStars: Int!
    var currentScore: CGFloat! {
        didSet {

            if currentScore < 0 {
                currentScore = 0
            } else if currentScore > CGFloat(numberOfStars) {
                currentScore = CGFloat(numberOfStars)
            }

        }
    }

    let ForegroundStarImage = "xj_2"
    let BackgroundStarImage = "xj_1"

    init(frame: CGRect, numberOfStars: Int, rateStyle: RateStyle, isAnimation: Bool, currentScore: CGFloat) {
        super.init(frame: frame)

        self.numberOfStars = numberOfStars
        self.rateStyle = rateStyle
        self.isAnimation = isAnimation
        self.currentScore = currentScore

        createStarView()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.numberOfStars = 5
        self.rateStyle = .halfStar
        self.isAnimation = false
        self.currentScore = 0

        createStarView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Private Method
    fileprivate func createStarView() {
        foregroundStarView = createStarViewWithImage(ForegroundStarImage)
        backgroundStarView = createStarViewWithImage(BackgroundStarImage)
        foregroundStarView.frame = CGRect(x: 0, y: 0, width: bounds.size.width * currentScore / CGFloat(numberOfStars), height: bounds.size.height)

        addSubview(backgroundStarView)
        addSubview(foregroundStarView)
    }

    fileprivate func createStarViewWithImage(_ imageName: String) -> UIView {
        let view = UIView(frame: self.bounds)
        view.clipsToBounds = true
        view.backgroundColor = UIColor.clear

        for i in 0..<numberOfStars {
            let imageView = UIImageView(image: UIImage(named: imageName))
            imageView.frame = CGRect(x: CGFloat(i) * bounds.size.width / CGFloat(numberOfStars), y: 0, width: bounds.size.width / CGFloat(numberOfStars), height: bounds.size.height)
            imageView.contentMode = UIView.ContentMode.scaleAspectFit
            view.addSubview(imageView)
        }

        return view
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let animationTimeInterval = isAnimation ? 0.2 : 0

        UIView.animate(withDuration: animationTimeInterval, animations: {
            self.foregroundStarView.frame = CGRect(x: 0, y: 0, width: self.bounds.width * self.currentScore / CGFloat(self.numberOfStars), height: self.bounds.height)
        })
    }

}
